<template>
  <div class="app-container">
    <el-form :inline="true" :model="recordInfo.queryForm" class="demo-form-inline">
      <el-form-item label="手机号">
        <el-input v-model="recordInfo.queryForm.mobile" @clear="clearMobile" placeholder="手机号" :maxlength="11" @input="handleMobileInput"
          clearable />
      </el-form-item>
      <!-- <el-form-item label="用户名">
        <el-input v-model="recordInfo.queryForm.userName" placeholder="用户名" clearable :maxlength="30" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="recordInfo.queryForm.mobile" placeholder="手机号" clearable type="number" :maxlength="20" />
      </el-form-item> -->

      <!-- <el-form-item label="来源渠道">
        <el-input v-model="recordInfo.queryForm.sourchann" placeholder="来源渠道" clearable :maxlength="20" />
      </el-form-item> -->

      <!-- <el-form-item label="年龄分组" filterable>
        <el-select v-model="recordInfo.queryForm.ageGrp" placeholder="请选择">
          <el-option v-for="item in ageGrpOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="易购卡">
        <el-select v-model="recordInfo.queryForm.storeMemberCardQuantityTotal" clearable placeholder="易购卡" style="width: 220px">
          <el-option v-for="item in cardTypeList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="会员来源">
        <el-select v-model="recordInfo.queryForm.sourWays" clearable placeholder="会员来源" style="width: 220px">
          <el-option v-for="item in memberSourceList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="会员状态">
        <el-select v-model="recordInfo.queryForm.memberStatus" clearable placeholder="会员状态" style="width: 220px">
          <el-option v-for="item in memberStatusList" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="注册时间">
        <el-date-picker v-model="registerTimeValue" type="daterange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :default-time="defaultTime"
          @change="dateChange('registerTimeValue')" style="width: 300px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
        <!-- <el-button @click="openDetail(1)">打开弹窗</el-button>
        <el-button @click="editMember1(1)">打开编辑</el-button> -->
      </el-form-item>

    </el-form>

    <el-table ref="multipleTable" v-loading="recordInfo.loading" class="table-default" highlight-current-row
      :data="recordInfo.list">
      <el-table-column type="index" label="序号" width="60" align="center" />

      <el-table-column label="会员信息" align="center">
        <template slot-scope="scope">
          <div class="member-info-cell" style="display: flex; align-items: center;justify-content: center;">
          <image-show :md5="scope.row.photoDownloadCode || ''" style="width:40px;height:40px;margin-right: 10px;" />
            <div class="member-text">
              <div class="name">{{ scope.row.nickName || '--' }}</div>
              <div class="id-phone">ID: {{ scope.row.userId || '--' }}</div>
              <div class="id-phone">{{ scope.row.userVO.mobile || '--' }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="userId" label="ID号" width="100" align="center" /> -->
      <!-- <el-table-column prop="nickName" label="会员昵称" width="200" align="center" /> -->
      <!-- <el-table-column prop="userVO.mobile" label="电话号码" width="180" align="center" /> -->
      <el-table-column prop="point" label="可用积分" width="180" align="center" />
      <!-- <el-table-column prop="balance" label="可用余额" width="130" align="center" /> -->
      <el-table-column prop="storeMemberCardQuantityTotal" label="易购卡数量" width="180" align="center" />
      <el-table-column prop="storeMemberCardBalanceTotal" label="易购卡余额" width="180" align="center" />
      <!-- <el-table-column prop="" label="VIP等级" width="80" align="center" />
      <el-table-column prop="" label="SVIP等级" align="center" /> -->
      <!-- <el-table-column prop="userVO.sex" label="性别(人工/识别)" align="center" /> -->
      <!-- <el-table-column prop="birthday" label="生日" align="center" /> -->
      <el-table-column prop="crtTm" label="注册时间" align="center" width="180" />
      <!-- <el-table-column prop="firstLoginTm" label="首次登录时间" align="center" /> -->
      <el-table-column prop="lastLoginTm" label="最近一次登录时间" width="180" align="center" />

      <el-table-column prop="lastConsumTm" label="多少天未购买" width="180" align="center" />
      <el-table-column label="操作" fixed="right" width="140" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="openDetail(scope.row)">详情</el-button>
          <!-- <el-button type="text" size="small" @click="editMember(scope.row)">编辑</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="recordInfo.total > 0" :total="recordInfo.total" :page.sync="recordInfo.queryForm.page"
      :limit.sync="recordInfo.queryForm.pageSize" @pagination="getRecordList" />
    <member-detail-dialog :visible.sync="showDetailDialog" :detail-data="currentMember" />
    <member-edit-dialog :visible.sync="showEditDialog" :member-id="currentMemberId" @success="handleSaveSuccess" />
  </div>
</template>

<script>
import filters from '@/filters/index'
import ListMixin from '@/mixins/modules/list'
import messageMixin from '@/mixins/modules/message'
import Pagination from '@/components/Pagination'
import MemberDetailDialog from './components/MemberDetailDialog.vue'
import MemberEditDialog from './components/MemberEditDialog.vue'
import imageShow from '@/components/imageShow'

export default {
  components: {
    Pagination,
    MemberDetailDialog,
    imageShow,
    MemberEditDialog
  },
  filters: {
    ...filters
  },
  mixins: [ListMixin, messageMixin],
  data() {
    return {
      // 绑定到日期选择器的值
      registerTimeValue: null,
      showEditDialog: false,
      showDetailDialog: false,
      currentMemberId: null,
      currentMember: null,
      autoGetList: false,
      recordInfo: {
        queryForm: {
          page: 1,
          userId: '',
          pageSize: 10,
          mobile: '', // 手机号
          sourWays: '', // 会员来源 1微信 2和3都是收银机(传3就可以),4后台添加,5扫商品码
          storeMemberCardQuantityTotal: '',  // 0 为绑卡 1绑卡
          returnCount: true,
          orderBy: 'createTimeDesc',
          orderState: 10,
          searchContent: '',
          createTimeStart: '',
          createTimeEnd: '',
          scoreMoreThenTargetScore: '',
          notSubmit: {
            searchOrganizationId: '',
            organizationNameSearchOrganizationId: '',
            supplierOrganizationNameSearchSupplierOrganizationId: '',
            searchSupplierOrganizationId: ''
          }
        },
        requestUrl: this.$api.getMemberInfoZgList, // 请求列表在api
        list: [], // 会员信息列表
        total: 0
      },
      ageGrpOptions: [{
        value: '1',
        label: '19-24（青年）'
      }, {
        value: '2',
        label: '25-35（青壮年）'
      }, {
        value: '3',
        label: '36-46（青大叔）'
      }, {
        value: '4',
        label: '47-57（大叔）'
      }, {
        value: '5',
        label: '58-78（青老年）'
      }, {
        value: '6',
        label: '>79老年人'
      }, {
        value: '7',
        label: '未知'
      }, {
        value: '99',
        label: '自定义n~n岁'
      }], // 年龄段分组
      cardTypeList: [{ name: '未办易购卡', value: 0 }, { name: '已办易购卡', value: 1 }],
      memberSourceList: [{ name: '微信小程序', value: 1 }, { name: '收银机', value: 3 }, { name: '后台添加', value: 4 }, { name: '扫商品码', value: 5 }],
      memberStatusList: [{ name: '正常', value: 1 }, { name: '禁用', value: 2 }],
      getListCallback(res) {
        if (res?.list?.length > 0) {
          let item
          for (let i = 0; i < res.list.length; i++) {
            item = res.list[i]
            const {
              firstLoginTm,
              lastLoginTm,
              crtTm,
              storeMemberCardBalanceTotal,
              lastConsumTm,
              birthdaySys
            } = item
            if (lastConsumTm) {
              if (res.list[i].lastConsumTm == 0) {
                res.list[i].lastConsumTm = '从未购买';
              } else {
                const currentTime = new Date();
                res.list[i].lastConsumTm = this.getDaysDifference(this.$commonUtils.getShowTime(lastConsumTm), currentTime) + '天';
              }
            }
            res.list[i].balance = '¥'  +  this.$amountUtils.getYuan(res.list[i].balance)
            res.list[i].storeMemberCardBalanceTotal && (res.list[i].storeMemberCardBalanceTotal = '¥'  +  this.$amountUtils.getYuan(storeMemberCardBalanceTotal))
            if (firstLoginTm) {
              res.list[i].firstLoginTm = this.$commonUtils.getShowTime(firstLoginTm)
            }
            if (crtTm) {
              res.list[i].crtTm = this.$commonUtils.getShowTime(crtTm)
            }
            if (lastLoginTm) {
              res.list[i].lastLoginTm = this.$commonUtils.getShowTime(lastLoginTm)
            }
            if (birthdaySys) {
              res.list[i].birthdaySys = this.$commonUtils.getShowTime(birthdaySys)
            }
          }
        }
      }
    }
  },
  created() {
    const query = this.$route.query
    if (undefined !== query) {
      try {
        const params = JSON.parse(decodeURIComponent(this.$Base64.decode(query.params)))
        if (undefined !== params) {
          console.log(params)
        }
      } catch (e) {
        // nothing
      }
    }
    this.getRecordList()
  },
  methods: {
    clearMobile() {
      this.recordInfo.queryForm.mobile = '';
      this.recordInfo.queryForm.userId = '';
    },
    handleMobileInput(value) {
      const mobileNumber = value.trim();
      if (mobileNumber.length === 11) {
        console.log('手机号大于七位，触发查询请求:', mobileNumber);
        this.$api.getMemberInfoList({
          returnUserDetail: true,
          returnCount: false,
          orderBy: 'createTimeDesc',
          mobile: mobileNumber,
          pageSize: 100,
          page: 1
        }).then(response => {
            console.log('查询结果:', response.list);
            if (response.list && response.list.length > 0) {
              this.recordInfo.queryForm.userId = response.list[0].userId;
            }
            // 处理查询结果
          })
          .catch(error => {
            console.error('查询出错:', error);
          });
      }
    },
    /**
 * 计算两个日期之间相差的天数
 * @param {Date | string | number} date1 - 第一个日期（例如：上次消费时间）
 * @param {Date | string | number} date2 - 第二个日期（例如：当前时间）
 * @returns {number} 相差的天数（向下取整）
 */
    getDaysDifference(date1, date2) {
      const d1 = new Date(date1);
      const d2 = new Date(date2);
      d1.setHours(0, 0, 0, 0);
      d2.setHours(0, 0, 0, 0);
      const diffTime = Math.abs(d2.getTime() - d1.getTime());
      const oneDay = 1000 * 60 * 60 * 24;
      const diffDays = Math.round(diffTime / oneDay);

      return diffDays;
    },
    resetForm() {
      // 业务字段清空
      this.recordInfo.queryForm = {
          page: 1,
          nickName: '',
          pageSize: 10,
          mobile: '', // 手机号
          sourWays: '', // 会员来源 1微信 2和3都是收银机(传3就可以),4后台添加,5扫商品码
          storeMemberCardQuantityTotal: '',  // 0 为绑卡 1绑卡
          returnCount: true,
          orderBy: 'createTimeDesc',
          orderState: 10,
          searchContent: '',
          createTimeStart: '',
          createTimeEnd: '',
          scoreMoreThenTargetScore: '',
          notSubmit: {
            searchOrganizationId: '',
            organizationNameSearchOrganizationId: '',
            supplierOrganizationNameSearchSupplierOrganizationId: '',
            searchSupplierOrganizationId: ''
          }
      }
      // 日期清空
      this.registerTimeValue = null
      // 重新查询
      this.init()
    },
    init() {
      this.recordInfo.list = []
      this.getRecordList()
      this.multipleSelection = []
    },
    openDetail(row) {
      this.currentMember = row
      this.showDetailDialog = true
    },
    editMember1(item) {
      // 设置要编辑的会员ID
      this.currentMemberId = item.memberId
      this.showEditDialog = true
    },
    // 查看会员详情 (跳转新 Tab)
    goDetail(item) {
      this.$addTab('memberDetailForm', {
        memberId: item.memberId
      }, '会员详情 - ' + item.memberName)
    },

    handleSaveSuccess() {
      this.showEditDialog = false
      // this.getRecordList()
    },

    // 编辑会员信息 (跳转新 Tab)
    editMember(item) {
      this.$addTab('memberEditForm', {
        memberId: item.memberId
      }, '编辑会员 - ' + item.memberName)
    },

    search() {
      this.recordInfo.queryForm.page = 1
      this.recordInfo.list = []
      this.getRecordList()
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  margin-top: 20px;
  font-size: 14px;

  .statistics-item {
    margin-left: 10px;
  }

  .value {
    color: #F07505;
    font-weight: bold;
  }
}
</style>
